import React, { useEffect, useRef } from 'react';
import { useSearchParams, useLocation } from 'react-router-dom'
const PowerBi = () => {
    const ifacmeRef = useRef(null)
    const [params] = useSearchParams()
    const code = params.get("code")
    const location = useLocation()
    useEffect(() => {
        const frame = ifacmeRef.current
        console.log(location.pathname, code)
        const handleLoad = () => {
            //向子页面传递消息
            if (frame && frame.contentWindow) {
                // 发送当前页面路径
                if (code) {
                    frame.contentWindow.postMessage(
                        {
                            type: 'code',
                            path: location.pathname,
                            addr: `${window.location.protocol}//${window.location.host}`,
                            code: code
                        },
                        'http://127.0.0.1:3000/' // 替换为 iframe 的实际域名
                    );
                }
                else {
                    frame.contentWindow.postMessage(
                        {
                            type: 'path',
                            path: location.pathname,
                            addr: `${window.location.protocol}//${window.location.host}`
                        },
                        'http://127.0.0.1:3000/' // 替换为 iframe 的实际域名
                    );
                }
            }
        };
        // 监听来自 iframe 的消息
        const handleMessage = (event) => {
            // 验证消息来源的域名，确保安全
            if (event.data.type !== "refresh") {
                // console.warn("不可信的消息来源:", event.origin);
                return;
            }
            window.location.href = event.data.url
        };

        // 添加加载监听
        frame.addEventListener('load', handleLoad);
        // 添加事件监听器
        window.addEventListener("message", handleMessage);
        // 清理函数
        return () => {
            frame.removeEventListener('load', handleLoad);
            window.removeEventListener("message", handleMessage);
        };
    }, [])

    return (
        <div style={{ height: "100%", overflow: "hidden" }}>
            <iframe
                src="http://127.0.0.1:3000/mmgdigitalbrain/page3"  // 填写实际嵌入MMG数字化企业大脑系统的页面地址
                width="100%"
                height="100%"
                ref={ifacmeRef}
                style={{ tableLayout: "fixed", height: "100%", padding: '10px' }}
                // style={{ border: '1px solid black' }} 
                title="Example Iframe"
            />
        </div>
    );
};

export default PowerBi;